from datetime import datetime

from werkzeug.security import generate_password_hash, check_password_hash

# from info import constants
from info import constants
from . import db


class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""
    create_time = db.Column(db.DateTime, default=datetime.now)  # 记录的创建时间
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间


# 用户收藏表，建立用户与其收藏新闻多对多的关系
tb_user_collection = db.Table(
    "mi_user_collection",
    db.Column("user_id", db.Integer, db.ForeignKey("mi_user.u_id"), primary_key=True),  # 用户编号
    db.Column("goods_id", db.Integer, db.ForeignKey("mi_goods.g_id"), primary_key=True),  # 商品编号
    db.Column("create_time", db.DateTime, default=datetime.now)  # 收藏创建时间
)

# 购物车与商品之间的关系
tb_join_shop_car = db.Table(
    "mi_join_shop_car",
    db.Column("shop_car_id", db.Integer, db.ForeignKey("mi_shopcart.sc_id"), primary_key=True),  # 购物车编号
    db.Column("goods_id", db.Integer, db.ForeignKey("mi_goods.g_id"), primary_key=True),  # 商品编号
)


class User(BaseModel, db.Model):
    """用户表"""
    __tablename__ = "mi_user"

    u_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 用户编号
    user_id = db.Column(db.String(32), nullable=False)
    nick_name = db.Column(db.String(32), nullable=False, default=user_id)  # 用户昵称
    real_name = db.Column(db.String(32))
    password_hash = db.Column(db.String(128), nullable=False)  # 加密的密码
    mobile = db.Column(db.String(11), nullable=False)  # 手机号
    avatar_url = db.Column(db.String(256))  # 用户头像路径
    id_card = db.Column(db.String(50))  # 身份证
    birthday = db.Column(db.DateTime)  # 生日
    last_login = db.Column(db.DateTime, default=datetime.now)  # 最后一次登录时间
    e_mail = db.Column(db.String(50))  # 邮箱
    rg_time = db.Column(db.DateTime)  # 注册时间
    user_blance = db.Column(db.Float, )  # 账户余额
    is_admin = db.Column(db.Boolean, default=False)  # 是否为管理员
    signature = db.Column(db.String(512))  # 用户签名
    user_stutas = db.Column(db.Boolean, default=0)  # 用户状态 默认未登录
    area_addr = db.Column(db.String(100))  # 居住地址
    bind_mobile = db.Column(db.String(11))  # 需要绑定的手机号
    bind_e_mail = db.Column(db.String(50))  # 绑定邮箱
    status = db.Column(db.Boolean, default=False)  # 激活码状态
    activekey = db.Column(db.String(50))  # 激活码
    mobile_status = db.Column(db.Boolean, default=False)  # 手机号绑定状态
    zfmm_password = db.Column(db.String(128), nullable=False, default='123456')

    gender = db.Column(
        db.Enum(
            "MAN",  # 男
            "WOMAN",  # 女
            "SECRECY",  # 保密
        ),
        default="MAN")
    # 当前用户收藏的所有商品
    collection_goods = db.relationship("Goods", secondary=tb_user_collection, lazy="dynamic")  # 用户收藏的商品
    rece_list = db.relationship("Receiving", backref="user", lazy='dynamic')  # 关联收货信息 一对多
    user_order = db.relationship("Order", backref="user", lazy="dynamic")  # 用户订单
    user_cart = db.relationship("Shop_cart", backref="user", lazy="dynamic")  # 用户购物车

    def to_dict(self):
        resp_dict = {
            "id": self.u_id,
            "user_id": self.user_id,
            "nick_name": self.nick_name,
            "avatar_url": constants.QINIU_DOMIN_PREFIX + self.avatar_url if self.avatar_url else "",
            'real_name': self.real_name,
            "mobile": self.mobile,
            "gender": self.gender if self.gender else "MAN",
            "e_mail": self.e_mail,
            "birthday": self.birthday,
            "area_addr": self.area_addr,
            "rece_list": self.rece_list,
            'mobile_status': self.mobile_status,
            'status': self.status
        }
        return resp_dict

    @property
    def password(self):
        raise AttributeError("当前属性不允许读取")

    @password.setter
    def password(self, value):
        # self.password_hash = 对value加密
        self.password_hash = generate_password_hash(value)

    def check_password(self, password):
        """校验密码"""
        return check_password_hash(self.password_hash, password)


class Category(BaseModel, db.Model):
    """分类表"""
    __tablename__ = "mi_category"

    c_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 分类id
    c_name = db.Column(db.String(25), )  # 分类名称
    p_id = db.Column(db.Integer, )  # 父id
    goods_list = db.relationship("Goods", backref="category", lazy="dynamic")  # 商品列表

    def to_dict(self):
        resp_dict = {
            "c_id": self.c_id,
            'c_name': self.c_name,

        }
        return resp_dict


class Goods(BaseModel, db.Model):
    """商品表"""
    __tablename__ = "mi_goods"

    g_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 商品id
    g_name = db.Column(db.String(50), nullable=False)  # 商品名称
    g_image = db.Column(db.String(256))  # 图片路径
    g_price = db.Column(db.Integer, nullable=False)  # 商品单价
    g_content = db.Column(db.String(256))  # 商品描述
    discount = db.Column(db.Float, default=1.0)
    inventory = db.Column(db.Integer, )  # 商品库存
    category_id = db.Column(db.Integer, db.ForeignKey("mi_category.c_id"))  # 商品分类
    merchant_id = db.Column(db.Integer, db.ForeignKey("mi_merchant.m_id"))  # 商品所属商家

    def to_dict(self):
        # print('商品内容-----------------', self.g_content)
        # print('商品内容长度', len(self.g_content))
        if len(self.g_name) >= 12:
            g_name = self.g_name[0:12] + '...'

        else:
            g_name = self.g_name

        if len(self.g_content) >= 12:
            g_content = self.g_content[0:12] + '...'
        else:
            g_content = self.g_content
        resp_dict = {
            'g_id': self.g_id,
            "g_name": g_name,
            'g_image': self.g_image,
            'g_price': self.g_price,
            "g_content": g_content,
            "category_id": self.category_id,
            'inventory': self.inventory,
            "merchant_id": self.merchant_id,
            'merchant_name': self.merchant.m_name
        }
        return resp_dict


class Merchant(BaseModel, db.Model):
    """商家表"""
    __tablename__ = 'mi_merchant'
    m_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 商家id
    m_name = db.Column(db.String(50), )  # 商家名字
    m_goods_list = db.relationship("Goods", backref='merchant', lazy='dynamic')  # 该商家的商品


class Shop_cart(BaseModel, db.Model):
    """购物车表"""
    __tablename__ = "mi_shopcart"
    sc_id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 购物车id
    # good_count = db.Column(db.Integer)  # 商品数量
    # all_price = db.Column(db.Integer)  # 总价
    # c_good_id = db.Column(db.Integer, db.ForeignKey("mi_goods.g_id"))  # 商品id
    c_user_id = db.Column(db.Integer, db.ForeignKey("mi_user.u_id"))  # 用户id
    shop_goods = db.relationship("Goods", secondary=tb_join_shop_car, lazy="dynamic")  # 购物车加入的商品
    # od_id = db.Column(db.Integer, db.ForeignKey("mi_order_detail.od_id"))  # 商品订单id


class Receiving(BaseModel, db.Model):
    """收货详情表"""

    __tablename__ = "mi_receiving"
    r_id = db.Column(db.Integer, autoincrement=True, primary_key=True)  # 收货信息id
    r_name = db.Column(db.String(50))  # 收货人姓名
    r_mobile = db.Column(db.String(11))  # 手机号
    r_addr_area = db.Column(db.String(50))  # 收货地区
    r_addr = db.Column(db.String(50))  # 详情地址
    user_id = db.Column(db.Integer, db.ForeignKey("mi_user.u_id"))  # 用户id


class Order(BaseModel, db.Model):
    """订单表"""
    __tablename__ = "mi_order"

    o_id = db.Column(db.Integer, autoincrement=True, primary_key=True)  # 订单id
    # o_pay_type = db.Column(db.Integer(2), comment="1.在线支付,2货到付款")
    o_start_time = db.Column(db.DateTime)  # 下单时间
    o_status = db.Column(db.Enum("-1", "0", "1"), default="-1")  # -1 未发货 0已发货 1已收货 订单状态
    o_manager = db.Column(db.String(50))  # 审核人
    o_last_time = db.Column(db.DateTime)  # 订单结束时间
    rece_id = db.Column(db.Integer, db.ForeignKey("mi_receiving.r_id"), nullable=False)  # 收货信息id
    o_user_id = db.Column(db.Integer, db.ForeignKey("mi_user.u_id"), nullable=False)  # 用户id
    user_msg = db.Column(db.String(256))  # 用户留言注释
    wl_name = db.Column(db.String(50))  # 物流名称
    wl_num = db.Column(db.String(100))  # 物流单号


class OrderDetail(BaseModel, db.Model):
    """商品订单表"""
    __tablename__ = "mi_order_detail"

    od_id = db.Column(db.Integer, autoincrement=True, primary_key=True)  # 详情id
    o_goods_id = db.Column(db.Integer, db.ForeignKey("mi_goods.g_id"))  # 商品id
    goods_num = db.Column(db.Integer)  # 商品数量
    goods_price = db.Column(db.String(50))  # 商品单价
    total_price = db.Column(db.String(50))  # 订单金额
